package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
	public final String driver = "com.mysql.jdbc.Driver";
	public final String url = "jdbc:mysql://localhost:3306/es";
	public final String username = "root";
	public final String password = "root";
	public Connection getConn() {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("加载驱动失败");
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("创建连接失败");
		}
		return conn;
	}
	public int exeUpd(String sql,String[] params) {
		int flag = 0;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs=null;
		conn = this.getConn();
		try {
			ps = conn.prepareStatement(sql);
			for(int i=0;i<params.length;i++) {
				ps.setString(i+1, params[i]);
			}
			flag = ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			this.closeAll(conn, ps, rs);
		}
		
		return flag;
	}
	public void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(ps!=null) {
				ps.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

